/**
 * @desc 客户管理
 * @author yd_zhaorongjun
 */
<template>
  <div class="gl_contentBox gl_heightFull" @click="cliclEmptyChange">
    <!-- <div class="gl_row_box gl_mb_15">共有客户XX家，专业版XX家，试用XX家</div> -->
    <div class="demo-input-suffix gl_searchBox">
      <el-row :gutter="20">
        <el-col :md="6" :lg="4">
          <p>{{ $t('search.platformType') }}</p>
          <el-select v-model="Api_GET_TenantsQO.EditionId" size="mini" :placeholder="$t('search.placeholder_PlatformType')" filterable @change="refreshList()">
            <el-option value="" label="全部" />
            <el-option v-for="item in editionsList" :key="item.id" :label="item.displayName" :value="item.id" />
          </el-select>
        </el-col>
        <!-- 按地区 -->
        <el-col :md="6" :lg="4">
          <p>{{ $t('search.region') }}</p>
          <el-select v-model="Api_GET_TenantsQO.Province" size="mini" :placeholder="$t('search.placeholder_Region')" filterable @change="refreshList()">
            <el-option value="" label="全部" />
            <el-option v-for="item in cache.district" :key="item.code" :label="item.name" :value="item.code" />
          </el-select>
        </el-col>
        <!-- 按状态 -->
        <el-col :md="6" :lg="4">
          <p>{{ $t('search.state') }}</p>
          <el-select v-model="Api_GET_TenantsQO.State" size="mini" :placeholder="$t('search.placeholder_State')" filterable @change="refreshList()">
            <el-option value="" label="全部" />
            <el-option :value="0" :label="$t('table.enable')" />
            <el-option :value="1" :label="$t('table.disable')" />
          </el-select>
        </el-col>
        <!-- 按创建人 -->
        <el-col :md="6" :lg="4">
          <p>{{ $t('search.creator') }}</p>
          <template>
            <el-row>
              <el-col :span="24">
                <div style="position:relative">
                  <div class="mock_input" :class="[collageListShow ? 'active' : '']" @click.stop="changePullStatus">
                    <el-input
                      v-model="Api_GET_TenantsQO.CreatorId"
                      type="text"
                      size="mini"
                      disabled
                    />
                  </div>
                  <div class="icon_pull gl_clear" @click.stop="changePullStatus">
                    <span class="placeholder_info" :class="Api_GET_TenantsQO.editionName==''? '':'placeholder_info_color' ">{{ Api_GET_TenantsQO.editionName || $t('tenant.pleaseSelect') + $t('search.creator') }}</span>
                    <i v-if="Api_GET_TenantsQO.editionName" class="el-select__caret el-input__icon el-icon-circle-close gl_fr" @click="clickClearEditionName" />
                    <i v-else class="gl_fr" :class="iconClass" />
                  </div>
                </div>
                <!-- 下拉列表 -->
                <div v-show="collageListShow" class="list_pull_style" @click.stop="collageListShow=true">
                  <div class="all_info_box">
                    <div class="info_left">
                      <el-tree :data="organizationUnitsTree" :props="defaultProps" :expand-on-click-node="false" node-key="code" @node-click="handleNodeClick" />
                    </div>
                    <div v-loading="info_right_loading" class="info_right">
                      <ul v-if="organizationUnitsUsers && organizationUnitsUsers.length>0">
                        <el-radio-group v-model="radio">
                          <li v-for="(data, index) in organizationUnitsUsers" :key="index" style="height:26px" @click.stop="getData(data)">
                            <el-radio :label="data.id">{{ data.name }}{{ data.phoneNumber }}</el-radio>
                          </li>
                        </el-radio-group>
                      </ul>
                      <div v-else style="width:90px" />
                    </div>
                  </div>
                  <div class="popper__arrow" />
                </div>
              </el-col>
            </el-row>
          </template>
        </el-col>
        <!-- 创建日期 -->
        <el-col :md="7" :lg="6" :xl="4">
          <p>{{ $t('search.creationDate') }}</p>
          <el-date-picker
            v-model="freeDay"
            type="daterange"
            :range-separator="$t('search.to')"
            :start-placeholder="$t('search.placeholder_Date')"
            :end-placeholder="$t('search.placeholder_Date')"
            size="mini"
            value-format="yyyy-MM-dd"
            style="width:100%"
            @change="timeChange"
          />
        </el-col>
        <!-- 名称 -->
        <el-col :md="6" :lg="4">
          <p>{{ $t('search.name') }}</p>
          <el-input v-model="Api_GET_TenantsQO.NameFilter" :placeholder="$t('search.placeholder_Name')" size="mini" clearable @change="refreshList()" />
        </el-col>
        <el-col :md="6" :lg="4">
          <!-- 查询按钮 -->
          <el-button style="margin-top:27px" type="primary" size="mini" @click="refreshList()">{{ $t('button.query') }}</el-button>
          <!-- 重置按钮 -->
          <el-button style="margin-top:27px" type="warning" size="mini" @click="refreshSearchForm">{{ $t('button.Reset') }}</el-button>
        </el-col>
      </el-row>
    </div>
    <template>
      <el-row :gutter="20" class="gl_my_15">
        <!-- 添加客户按钮 -->
        <el-col :md="6" :lg="4">
          <el-button type="success" size="mini" @click="editOfAdd()">{{ $t('button.addCustomer') }}</el-button>
        </el-col>
      </el-row>
      <el-table
        v-loading="loading"
        :data="tableData"
        stripe
        size="mini"
        :row-class-name="tableRowClassName"
        style="width: 100%;"
      >
        <!-- 客户名称 -->
        <el-table-column
          prop="name"
          :label="$t('table.customerName')"
          width="140"
        />
        <!-- 客户Id -->
        <el-table-column
          prop="id"
          label="客户Id"
          width="250"
        />
        <!-- 公司所在地 -->
        <el-table-column
          :label="$t('table.companyAddress')"
          width="180"
        >
          <template slot-scope="{row}">
            <span>
              {{ row.provinceName }}
              {{ row.provinceName && row.cityName ? ' - ' + row.cityName : row.cityName }}
              {{ row.cityName && row.countyName ? ' - ' + row.countyName : row.countyName }}
            </span>
          </template>
        </el-table-column>
        <!-- 版本类型 -->
        <el-table-column
          prop="editionName"
          :label="$t('table.editionName')"
          align="center"
          width="110"
        />
        <!-- 创建日期 -->
        <el-table-column
          :label="$t('table.creationTime')"
          align="center"
          width="140"
        >
          <template slot-scope="{row}">
            <span v-if="row.creationTime">
              {{ row.creationTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <!-- 结束提醒时间 -->
        <el-table-column
          label="结束提醒时间"
          align="center"
          width="140"
        >
          <template slot-scope="{row}">
            <span v-if="row.remindTime">
              {{ row.remindTime | FormatDate('yyyy-MM-dd HH:mm:ss') }}
            </span>
          </template>
        </el-table-column>
        <!-- 创建人 -->
        <el-table-column
          prop="creatorName"
          :label="$t('table.creator')"
          width="120"
        />
        <!-- 状态 -->
        <el-table-column
          :label="$t('table.status')"
          align="center"
          width="80"
        >
          <template slot-scope="{row}">
            <span v-if="row.state == 0" class="gl_color_success">
              <i class="el-icon-success" />
              <span class="gl_pl_5">{{ $t('table.enable') }}</span>
            </span>
            <span v-else class="gl_color_grey">
              <i class="el-icon-error" />
              <span class="gl_pl_5">{{ $t('table.disable') }}</span>
            </span>
          </template>
        </el-table-column>
        <!-- 描述 -->
        <el-table-column
          :label="$t('table.description')"
          :tooltip="true"
          min-width="200"
        >
          <template slot-scope="{row}">
            <el-popover
              placement="top-start"
              width="500"
              trigger="hover"
              :content="row.description"
            >
              <span slot="reference" class="gl_ellipsis">{{ row.description }}</span>
            </el-popover>
          </template>
        </el-table-column>
        <!-- 地址 -->
        <el-table-column :label="$t('table.addressUrl')" :tooltip="true" min-width="150">
          <template slot-scope="{row}">
            <el-popover placement="top-start" width="500" trigger="hover">
              <div style="text-align:left;">
                <span>{{ baseUrls + '#/?tenantid=' + row.id }} </span>
                <el-button style="margin:5px auto 0;display: block;" size="mini" type="primary" plain @click="handleCopy( baseUrls + '#/?tenantid=' + row.id)">复制</el-button>
              </div>
              <span slot="reference" class="gl_ellipsis">{{ baseUrls + '#/?tenantid=' + row.id }} </span>
            </el-popover>
          </template>
        </el-table-column>
        <!-- 操作 -->
        <el-table-column fixed="right" :label="$t('table.actions')" width="150">
          <template slot-scope="{row,$index}">
            <!-- 编辑按钮 -->
            <el-button size="mini" type="text" @click="editOfAdd(row,$index)">
              {{ $t('table.edit') }}
            </el-button>
            <!-- 禁用按钮 -->
            <el-button v-if="row.state == 0" size="mini" type="text" @click="clickDisable(row)">
              <span class="gl_color_warning">{{ $t('table.disable') }}</span>
            </el-button>
            <!-- 启用按钮 -->
            <el-button v-else size="mini" type="text" @click="clickEnable(row)">
              <span class="gl_color_warning">{{ $t('table.enable') }}</span>
            </el-button>
            <!-- 删除按钮 -->
            <!-- <el-button v-if="row.state == 1" size="mini" type="text" @click="clickDelete(row)">
              <span class="gl_color_error">{{ $t('table.delete') }}</span>
            </el-button> -->
          </template>
        </el-table-column>
      </el-table>

      <el-row class="gl_pt_20" style="text-align: center;">
        <el-pagination
          :current-page="Api_GET_TenantsQO.Page"
          :page-size="Api_GET_TenantsQO.MaxResultCount"
          :total="totalPage"
          layout="total,sizes,prev,pager,next,jumper"
          :page-sizes="[10, 20, 30, 40]"
          @size-change="sizeChange"
          @current-change="pageIndexChange"
        />
      </el-row>
    </template>

    <edit-customer ref="editCustomer" :delegation-type="dict.delegationType" :editions="editionsList" :district="cache.district" @insert="customerInsert" @update="customerUpdate" />
  </div>
</template>

<script>

import { mapState, mapActions } from 'vuex';
import { Api_GET_TenantsQO } from '@/lib/form/swaggerForm';
import { translateByCode } from '@/lib/getTransData';
import editCustomer from './editCustomer';
import { SaasTenantCreateDto } from '@/lib/form/swaggerForm';
import { CopyData } from '@/lib';
import { api_GET_Tenants, api_POST_Tenants, api_PUT_TenantsId, api_DELETE_TenantsId, api_GET_Editions } from '@/extend/api/swaggerApi/saas';
import { api_GET_OrganizationUnitsTree, api_GET_OrganizationUnitsIdUsers } from '@/extend/api/swaggerApi/identity.js'; // api接口
export default {
  name: 'TenantManagement',
  components: {
    editCustomer
  },
  data() {
    return {
      SaasTenantCreateDto: new SaasTenantCreateDto(),
      Api_GET_TenantsQO: new Api_GET_TenantsQO(),
      freeDay: [],
      loading: false,
      info_right_loading: false,
      totalPage: 0,
      tableData: [],
      provinceList: [], // 地区的下拉列表
      editionsList: [], // 版本的下拉
      editId: '', // 编辑时候的id
      currentPage: 1,
      collageListShow: false, // 控制下拉列表的显示隐藏
      radio: '', // 储存选择用户的信息
      organizationUnitsUsers: [], // 下拉列表显示的人员
      currentTreeDate: {}, // 获取树的组织架构
      iconClass: 'el-input__icon el-icon-arrow-down', // 下拉图标
      organizationUnitsTree: [], // 下拉列表左侧组织树结构
      defaultProps: {
        children: 'children',
        label: 'displayName'
      },
      baseUrls: window.location.origin + window.location.pathname,
      copyData: null
    };
  },
  computed: {
    ...mapState({
      cache: state => state.dict.cache,
      dict: state => state.dict.dict
    })
  },
  created() {
    this.getDictByType(['district']);
    this.getDict();
    this.getOrganizationUnitsTree();
    this.api_GET_Editions();
    this.Api_GET_TenantsQO.State = '';
    this.refreshList();
  },
  methods: {
    ...mapActions({ getDictByType: 'dict/getDictByType', getDict: 'dict/getDict' }),
    // 获取组织树结构
    getOrganizationUnitsTree() {
      api_GET_OrganizationUnitsTree().then(res => {
        this.organizationUnitsTree = res.items;
      }, (error) => {
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 获取版本下拉
    api_GET_Editions() {
      api_GET_Editions(this.Api_GET_TenantsQO).then(res => {
        this.editionsList = res.items;
      }, (error) => {
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 点击树获取当前组织结构数据
    handleNodeClick(data) {
      this.info_right_loading = true;
      this.currentTreeDate = data;
      this.getUserName();
    },
    // 获取用户列表
    getUserName() {
      api_GET_OrganizationUnitsIdUsers(this.currentTreeDate.id).then(res => {
        this.organizationUnitsUsers = res.items;
        this.info_right_loading = false;
      }, (error) => {
        this.info_right_loading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 点击radio获取表单框的元素
    getData (data) {
      this.Api_GET_TenantsQO.editionName = data.name;
      this.Api_GET_TenantsQO.CreatorId = data.id;
      this.radio = data.name;
      // this.collageListShow = false;
      this.iconClass = 'el-input__icon el-icon-arrow-down';
      this.refreshList();
    },
    // 点击图标
    changePullStatus() {
      if (this.iconClass === 'el-input__icon el-icon-arrow-down') {
        this.iconClass = 'el-input__icon el-icon-arrow-down is-reverse';
        this.collageListShow = true;
      } else {
        this.iconClass = 'el-input__icon el-icon-arrow-down';
        this.collageListShow = false;
      }
    },
    // 点击空白处收回下拉框
    cliclEmptyChange() {
      this.collageListShow = false;
      this.iconClass = 'el-input__icon el-icon-arrow-down';
    },
    // 搜索栏创建人的清除按钮
    clickClearEditionName() {
      event.stopPropagation();
      this.$set(this.Api_GET_TenantsQO, 'editionName', '');
      this.$set(this.Api_GET_TenantsQO, 'CreatorId', '');
      this.radio = '';
      this.collageListShow = false;
      this.refreshList();
    },
    // 刷新列表
    refreshList(page) {
      this.loading = true;
      this.Api_GET_TenantsQO.Page = page || 1;
      this.Api_GET_TenantsQO.SkipCount = (this.Api_GET_TenantsQO.Page - 1) * this.Api_GET_TenantsQO.MaxResultCount;
      api_GET_Tenants(this.Api_GET_TenantsQO).then(res => {
        this.tableData = res.items;
        this.totalPage = res.totalCount;
        this.loading = false;
      }, (error) => {
        this.loading = false;
        this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 重置搜索表单
    refreshSearchForm() {
      this.Api_GET_TenantsQO = new Api_GET_TenantsQO();
      this.Api_GET_TenantsQO.State = '';
      this.freeDay = [];
      this.refreshList();
    },
    // 为 Table 中的某一行添加 class
    tableRowClassName({ row, rowIndex }) {
      if (row.state === 1) {
        return 'gl_color_grey';
      }
      return '';
    },
    // 日历选择器给QO赋值
    timeChange(val) {
      if (val instanceof Array) {
        this.Api_GET_TenantsQO.StartCreationTime = this.freeDay[0];
        this.Api_GET_TenantsQO.EndCreationTime = this.freeDay[1];
      } else {
        this.Api_GET_TenantsQO.StartCreationTime = '';
        this.Api_GET_TenantsQO.EndCreationTime = '';
      }
      this.refreshList();
    },
    // 添加或修改用户
    editOfAdd(row) {
      this.editId = row ? row.id : '';
      this.$refs.editCustomer.open(row);
    },
    // 添加用户
    customerInsert(data) {
      const _this = this;
      api_POST_Tenants(data).then(res => {
        this.$message({
          // 添加成功！
          message: translateByCode('alert.addSuccessfully'),
          type: 'success'
        });
        _this.$refs.editCustomer.dialogVisible = false;
        _this.$refs.editCustomer.submitLoading = false;
        _this.refreshList();
      }, (error) => {
        _this.$refs.editCustomer.submitLoading = false;
        _this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 修改用户
    customerUpdate(data) {
      const _this = this;
      api_PUT_TenantsId(this.editId, data).then(res => {
        this.$message({
          // 修改成功！
          message: translateByCode('alert.editSuccessfully'),
          type: 'success'
        });
        _this.$refs.editCustomer.dialogVisible = false;
        _this.$refs.editCustomer.submitLoading = false;
        _this.refreshList(this.Api_GET_TenantsQO.Page);
      }, (error) => {
        _this.$refs.editCustomer.submitLoading = false;
        _this.$message({ type: 'error', message: error.error.message });
      });
    },
    // 禁用按钮api_PUT_TenantsId
    clickDisable(row) {
      const _this = this;
      CopyData(row, this.SaasTenantCreateDto);
      this.SaasTenantCreateDto.state = 1;
      const _confirmStr = ` ${translateByCode('alert.wantDisable')} [ ${row.name} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_PUT_TenantsId(row.id, this.SaasTenantCreateDto).then(res => {
          this.$message({
            type: 'success',
            // 禁用成功！
            message: translateByCode('alert.disableSuccessfully')
          });
          this.refreshList(this.Api_GET_TenantsQO.Page);
        }, (error) => {
          _this.$message({ type: 'error', message: error.error.message });
        });
      }).catch(() => {
      });
    },
    // 启用按钮api_PUT_TenantsId
    clickEnable(row) {
      const _this = this;
      CopyData(row, this.SaasTenantCreateDto);
      this.SaasTenantCreateDto.state = 0;
      const _confirmStr = ` ${translateByCode('alert.wantAble')} [ ${row.name} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_PUT_TenantsId(row.id, this.SaasTenantCreateDto).then(res => {
          this.$message({
            type: 'success',
            // 启用成功！
            message: translateByCode('alert.ableSuccessfully')
          });
          this.refreshList(this.Api_GET_TenantsQO.Page);
        }, (error) => {
          _this.$message({ type: 'error', message: error.error.message });
        });
      }).catch(() => {
      });
    },
    // 删除按钮
    clickDelete(row) {
      const _this = this;
      // 您确定要删除 xxx 吗？ zh
      const _confirmStr = ` ${translateByCode('alert.wantDelete')} [ ${row.name} ] ${translateByCode('alert.ma')}`;
      this.$confirm(_confirmStr, translateByCode('alert.warning'), {
        confirmButtonText: translateByCode('alert.confirm'),
        cancelButtonText: translateByCode('alert.cancel'),
        type: 'warning'
      }).then(() => {
        api_DELETE_TenantsId(row.id).then(res => {
          this.$message({
            type: 'success',
            // 删除成功！
            message: translateByCode('alert.deleteSuccessfully')
          });
          this.refreshList();
        }, (error) => {
          _this.$message({ type: 'error', message: error.error.message });
        });
      }).catch(() => {
      });
    },
    // 复制按钮
    handleCopy(data) {
      const url = data;
      const oInput = document.createElement('input');
      oInput.value = url;
      document.body.appendChild(oInput);
      oInput.select(); // 选择对象;
      console.log(oInput.value);
      document.execCommand('Copy'); // 执行浏览器复制命令
      this.$message({
        message: '复制成功',
        type: 'success'
      });
      oInput.remove();
    },
    sizeChange(MaxResultCount) {
      this.Api_GET_TenantsQO.MaxResultCount = MaxResultCount;
      this.refreshList();
    },
    pageIndexChange(currentPage) {
      this.refreshList(currentPage);
    }
  }
};
</script>
<style lang="scss">
.list_pull_style{
  position:absolute;
  z-index:8;
  min-width:380px;
  min-height:150px;
  border:1px solid #dfe4ed;
  background:#fff;
  padding:10px 10px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  margin:12px 0 5px 0;
  font-size: 14px;
  transition: all 0.3s linear;
}
.popper__arrow, .popper__arrow::after {
    position: absolute;
    display: block;
    width: 0;
    height: 0;
    border-color: transparent;
    border-style: solid;
}
.popper__arrow {
    top: -12px;
    left: 35px;
    margin-right: 3px;
    border-top-width: 0;
    border-bottom-color: #e6ebf5;
}
.popper__arrow {
    border-width: 6px;
    -webkit-filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
    filter: drop-shadow(0 2px 12px rgba(0, 0, 0, 0.03));
}

.popper__arrow::after {
    content: " ";
    border-width: 6px;
}
.popper__arrow::after {
    top: 1px;
    margin-left: -6px;
    border-top-width: 0;
    border-bottom-color: #FFFFFF;
}
.icon_pull{
  position:absolute;
  width: 100%;
  left:0;
  color: #C0C4CC;
  top:-5px;
  cursor: pointer;
}
.placeholder_info{
  position: relative;
  top:10px;
  left:15px;
}
.placeholder_info_color{
  color: #C0C4CC;
}
.all_info_box{
  display:flex;
  min-height:inherit
}
.info_left{
  min-width:120px;
}
.info_right{
  border-left:1px solid #dfe4ed;
  padding-left:20px;
  margin-left:20px;
  width:100%
}

.mock_input {
  box-sizing: content-box;
  height: 0;
  padding: 26px 15px 0;
  border: 1px solid #dfe4ed;
  border-radius: 4px;
  overflow: hidden;
  cursor: pointer;
  transition: 0.3s;
  background: #fff;
}
.mock_input.active {
  border: 1px solid #1890ff;
}
.mock_input.error {
  border: 1px solid #ff4949;
}
.infomation_box{
  text-align:center;
  height:60px;
  padding-top:20px;
}
.info_p_box{
  font-size:18px;
}
.change_super .el-input.is-disabled .el-input__inner{
  cursor: pointer;
  background: #FFFFFF;
  color: #000;
}

.change_super .el-icon-arrow-down.is-reverse {
    -webkit-transform: rotateZ(180deg);
    transform: rotateZ(180deg);
}
</style>
